<?php

namespace controller\api;

defined('IA_ROOT') || exit();

use mvc\Controller;
use facade\Model;
use facade\Util;

// 控制器
class Index extends Controller
{
    // 语言
    private $lang;
    private $langs;
    private $voice;
    private $localize;

    // 系统属性
    private $setting; //系统设置
    private $param; //请求参数
    private $site_url; //站点地址
    private $callback; //JSONP

    // 内容数据
    private $categories = []; //全部分类
    private $tags = []; //全部标签
    private $articles = []; //全部文章
    private $pages = []; //全部页面
    private $users = []; //全部用户数据
    private $comments = []; //全部评论
    private $links = []; //全部友链

    // 初始化
    protected function initialize()
    {
        // 语言
        $this->lang = Util::lang();
        $this->langs = array_map(function ($item) {
            $item['title'] = Util::tran($item['title']);
            return $item;
        }, Util::langs());
        $this->voice = Util::voice();

        // 系统属性
        $this->site_url = Util::url(); //站点地址
        $this->param = Util::param(); //请求参数
        $this->callback = isset($this->param['callback']) && $this->param['callback'] && preg_match('/^[a-zA-Z0-9_]+$/', $this->param['callback']) ? $this->param['callback'] : '';

        // 国际化串
        $this->localize = [
            'home' => Util::tran('首页'),
            'language' => Util::tran('语言'),
            'search' => Util::tran('搜索'),
            'choose_language' => Util::tran('选择语言'),
            'category_title' => Util::tran('分类目录'),
            'no_categories' => Util::tran('还没有分类'),
            'page_title' => Util::tran('页面'),
            'tag_title' => Util::tran('标签'),
            'articles' => Util::tran('篇文章'),
            'no_tags' => Util::tran('还没有标签'),
            'hot_title' => Util::tran('热门文章'),
            'no_hots' => Util::tran('还没有热门'),
            'uncategoried' => Util::tran('未分类'),
            'no_articles' => Util::tran('还没有文章'),
            'comment_title' => Util::tran('最新评论'),
            'say' => Util::tran('说道'),
            'no_comments' => Util::tran('还没有评论'),
            'no_pages' => Util::tran('还没有页面'),
            'friend_link' => Util::tran('友情链接'),
            'login' => Util::tran('登录'),
            'register' => Util::tran('注册'),
            'logout' => Util::tran('登出'),
            'client' => Util::tran('客户端'),
            'console' => Util::tran('控制台'),
            'audio_play' => Util::tran('语音播放'),
            'back_top' => Util::tran('回到顶部'),
            'newest' => Util::tran('最新文章'),
            'search_result' => Util::tran('搜索结果'),
            'page_not_found' => Util::tran('页面未找到'),
            'no_description' => Util::tran('还没有描述信息'),
            'sorry_not_found' => Util::tran('抱歉，你要访问的页面不存在！'),
            'untitled' => Util::tran('无标题'),
            'no_datas' => Util::tran('还没有数据'),
            'wechat' => Util::tran('微信'),
            'download_content' => Util::tran('下载内容'),
            'favorite_article' => Util::tran('收藏文章'),
            'copyr_info' => Util::tran('除非特别说明，本博客均为原创，如需转载，请以链接形式标明来源出处。'),
            'copyr_address' => Util::tran('本文博客网址'),
            'no_address' => Util::tran('还没有网址'),
            'article_useful' => Util::tran('这篇文章很有用'),
            'people_likes' => Util::tran('人觉得这篇文章很赞'),
            'nothing' => Util::tran('没有了'),
            'related_articles' => Util::tran('相关文章'),
            'post_comment' => Util::tran('发表评论'),
            'comment_content' => Util::tran('评论内容'),
            'please' => Util::tran('请'),
            'after_comment' => Util::tran('后评论'),
            'delete' => Util::tran('删除'),
            'reply' => Util::tran('回复'),
            'no_comment' => Util::tran('还没有评论'),
            'favorite_cancel' => Util::tran('取消收藏'),
            'favorite_success' => Util::tran('收藏成功'),
            'info' => Util::tran('信息'),
            'sure' => Util::tran('确定'),
            'switch_register' => Util::tran('切换注册'),
            'username' => Util::tran('用户名'),
            'username_or_email' => Util::tran('用户名或邮箱'),
            'password' => Util::tran('密码'),
            'input_password' => Util::tran('请输入密码'),
            'forget_password' => Util::tran('忘记密码'),
            'forget' => Util::tran('找回密码'),
            'switch_login' => Util::tran('切换登录'),
            'email_address' => Util::tran('邮箱地址'),
            'register_email' => Util::tran('您的注册邮箱'),
            'verycode' => Util::tran('验证码'),
            'fetch_verycode' => Util::tran('获取验证码'),
            'new_password' => Util::tran('新密码'),
            'input_new_password' => Util::tran('设置新密码'),
            'confirm_password' => Util::tran('确认密码'),
            'repeat_new_password' => Util::tran('确认新密码'),
            'submit' => Util::tran('提交'),
            'input_username' => Util::tran('请输入用户名'),
            'repeat_password' => Util::tran('重复密码'),
            'input_repeat_password' => Util::tran('请重输入密码'),
            'email' => Util::tran('邮箱'),
            'find_password_use' => Util::tran('找回密码用'),
            'optional' => Util::tran('可选'),
            'nickname' => Util::tran('昵称'),
            'phone' => Util::tran('手机'),
            'input_email_address' => Util::tran('请输入邮箱地址'),
            'email_format_error' => Util::tran('邮箱格式错误'),
            'sending' => Util::tran('发送中'),
            'resend' => Util::tran('重新发送'),
            'merging' => Util::tran('正在合成，请稍后'),
            'merge_success' => Util::tran('合成成功！再次点击按钮下载。'),
            'cancel_reply' => Util::tran('取消回复'),
            'reply_comment' => Util::tran('回复评论'),
            'scan_wechat' => Util::tran('微信扫一扫'),
            'share_email' => Util::tran('分享到邮箱'),
            'close' => Util::tran('关闭'),
            'send' => Util::tran('发送'),
            'logining' => Util::tran('登录中'),
            'redirecting' => Util::tran('跳转中'),
            'reseting' => Util::tran('重置中'),
            'registering' => Util::tran('注册中'),
            'submiting' => Util::tran('提交中'),
            'pending' => Util::tran('审核中')
        ];
    }

    // 模板赋值
    private function vars()
    {
        $vars = get_class_vars(__CLASS__);
        array_walk($vars, function (&$value, $key) {
            $value = $this->$key;
        });
        return $vars;
    }

    // 私有方法
    private function properties()
    {
        $default = [
            'webLogo' => '/static/images/brand.png',
            'webName' => 'Brand',
            'seo_title' => '',
            'seo_description' => '',
            'upload_type' => 'gif|jpg|jpeg|png|mp3|mp4|zip',
            'upload_size' => '2048',
            'robot_index' => '0',
            'alone_login' => '0',
            'copyright' => '&copy; 2021-' . date('Y') . ' Company, Inc.',
            'icp' => 'ICP No.001',
            'cdn_speed' => '0',
            'slide_image_1' => '',
            'slide_url_1' => '',
            'slide_image_2' => '',
            'slide_url_2' => '',
            'slide_image_3' => '',
            'slide_url_3' => '',
            'slide_image_4' => '',
            'slide_url_4' => '',
            'slide_image_5' => '',
            'slide_url_5' => '',
            'hot_num' => '5',
            'comm_num' => '5',
            'related_num' => '3',
            'page_num' => '24',
            'link_num' => 8,
            'voice_read' => '1',
            'can_comment' => '1',
            'pending_comment' => '1',
            'service' => '',
            // 'email' => '',
            // 'code' => '',
            'static' => '',
            'date' => '',
            'site' => ''
        ];
        $setting = Model::fetch('SELECT * FROM `setting` WHERE id=:id', [':id' => 1]);
        if ($setting) {
            $setting = json_decode($setting['value'], true);
            $setting = array_intersect_key($setting, $default);
            $setting = array_merge($default, $setting);
        } else {
            $setting = $default;
        }
        $setting['webName'] = Util::tran($setting['webName']);
        $setting['seo_title'] = Util::tran($setting['seo_title']);
        $setting['seo_description'] = Util::tran($setting['seo_description']);
        $setting['copyright'] = Util::tran($setting['copyright']);
        $setting['icp'] = Util::tran($setting['icp']);
        $this->setting = $setting;
    }

    // 首页
    public function index()
    {
        $this->properties();
        $lang = $this->lang == 'zh-TW' ? 'zh-CN' : $this->lang;

        // 分类数据
        $this->categories = Model::fetchAll("SELECT * FROM `category` WHERE `status` = 0 AND `lang` = '{$lang}' ORDER BY `id` ASC, `sort` DESC");

        // 标签数据
        $this->tags = Model::fetchAll("SELECT * FROM `tag` WHERE `status` = 0 AND `lang` = '{$lang}' ORDER BY `sort` DESC, `id` DESC");

        // 文章数据
        $this->articles = Model::fetchAll("SELECT * FROM `article` WHERE `status` = 0 AND `lang` = '{$lang}' ORDER BY `id` DESC");

        // 页面数据
        $this->pages = Model::fetchAll("SELECT * FROM `page` WHERE `status` = 0 AND `lang` = '{$lang}' ORDER BY `id` ASC, `sort` DESC");

        // 用户数据
        $this->users = Model::fetchAll("SELECT `id`, `username`, `nickname`, `avatar` FROM `user` WHERE `status` = 0 ORDER BY `id` DESC");

        // 评论数据
        $this->comments = Model::fetchAll("SELECT * FROM `comment` WHERE `status` = 0 AND `lang` = '{$lang}' ORDER BY `sort` DESC, `id` DESC");

        // 友链数据
        $this->links = Model::fetchAll("SELECT * FROM `link` WHERE `status` = 0  ORDER BY `id` ASC, `sort` DESC");

        // 输出数据
        Util::json(['code' => 0, 'msg' => 'success', 'data' => $this->vars()], $this->callback);
    }

    // 数据转发接口
    public function fetch()
    {
        $param = Util::param();
        $url = isset($param['url']) && $param['url'] ? $param['url'] : '';
        $method = isset($param['method']) && $param['method'] ? strtoupper($param['method']) : 'GET';
        if (isset($param['url'])) unset($param['url']);
        if (isset($param['method'])) unset($param['method']);
        echo Util::curl($url, $param, $method);
    }

    // 谷歌翻译接口
    public function google_translate()
    {
        $param = Util::param(['client', 'dj', 'dt', 'ie', 'oe', 'sl', 'tl', 'tk', 'q']);
        $ipArr = [
            '142.251.43.14', //中国/台湾/台北
            '142.251.220.14', //日本/大阪府/大阪
            '142.251.220.174', //日本/大阪府/大阪
            '142.250.68.46', //美国/加利福尼亚/洛杉矶
            '172.217.12.142', //骨干网
            '172.217.160.110', //骨干网
            '142.251.41.46', //日本/大阪府/大阪
            '142.250.69.206', //美国
            '142.251.222.238', //骨干网
            '172.217.31.142', //骨干网
            '142.251.175.113', //日本/大阪府/大阪
            '172.217.16.238', //西班牙/马德里
            '172.217.24.46', //中国/台湾/台北
            '142.250.71.78', //美国
            '142.251.163.113', //美国/弗吉尼亚/阿什本
            '216.58.215.238', //美国
            '172.217.163.46', //骨干网
            '142.251.132.14', //日本/大阪府/大阪
            '142.251.129.142', //日本/大阪府/大阪
            '192.178.54.78', //美国
        ];
        $ip = $ipArr[array_rand($ipArr)];
        if (!isset($param['q'])) $param['q'] = '';
        $data = array_merge([
            'client' => 'webapp', //参数为gtx不需tk值
            'dj' => '1',
            'dt' => 't',
            'ie' => 'UTF-8',
            'oe' => 'UTF-8',
            'sl' => 'zh-CN',
            'tl' => 'en',
            'tk' => $this->getTk($param['q'])
        ], $param);
        $header = [
            'Content-type: application/x-www-form-urlencoded',
            'X-Requested-With: XMLHttpRequest',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
            'Host: translate.google.com',
            'Referer: https://translate.google.com',
            'X-FORWARDED-FOR: ' . $ip,
            'CLIENT-IP: ' . $ip
        ];
        header('Content-type: application/json; charset=UTF-8');
        header('Access-Control-Allow-Origin: *');
        echo Util::curl('https://translate.google.com/translate_a/single', $data, 'POST', $header);
    }

    // 百度翻译接口
    public function baidu_translate()
    {
        $param = Util::param(['query', 'from', 'to', 'simple_means_flag', 'sign', 'token', 'domain']);
        if (!isset($param['query'])) $param['query'] = '';
        $data = array_merge([
            'from' => 'zh',
            'to' => 'en',
            'simple_means_flag' => '3',
            'sign' => $this->getTk($param['query'], 1),
            'token' => '853eba4bc7ac9601ef8fff761c7cf8cf',
            'domain' => 'common'
        ], $param);
        $header = [
            'Content-type: application/x-www-form-urlencoded',
            'X-Requested-With: XMLHttpRequest',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
            'Referer: https://fanyi.baidu.com',
            'Origin: https://fanyi.baidu.com',
            'Accept: text/event-stream',
            'Cookie: BAIDUID=BBAF98B01ABDC86AE4980FBD0367379A:FG=1'
        ];
        header('Content-type: application/json; charset=UTF-8');
        header('Access-Control-Allow-Origin: *');
        echo Util::curl('https://fanyi.baidu.com/v2transapi', $data, 'POST', $header);
    }

    // 谷歌百度翻译Tk算法（默认谷歌）
    private function getTk($a, $t = 0)
    {
        $gtk = $t ? '320305.131321201' : '406398.2087938574';
        $e = explode('.', $gtk);
        // 转换输入字符串为UTF-16代码单元数组
        $utf16 = mb_convert_encoding($a, 'UTF-16LE', 'UTF-8');
        $codeUnits = array();
        $len = strlen($utf16);
        for ($i = 0; $i < $len; $i += 2) {
            $codeUnit = ord($utf16[$i]) + (ord($utf16[$i + 1]) << 8);
            $codeUnits[] = $codeUnit;
        }
        $g = array();
        $d = 0;
        $f = 0;
        $codeUnitsCount = count($codeUnits);
        while ($f < $codeUnitsCount) {
            $c = $codeUnits[$f];
            if ($c < 0x80) {
                $g[$d++] = $c;
            } elseif ($c < 0x800) {
                $g[$d++] = ($c >> 6) | 0xC0;
                $g[$d++] = ($c & 0x3F) | 0x80;
            } else {
                if (($c & 0xFC00) === 0xD800 && $f + 1 < $codeUnitsCount && ($codeUnits[$f + 1] & 0xFC00) === 0xDC00) {
                    // 处理四字节UTF-8（代理对）
                    $c = 0x10000 + (($c & 0x3FF) << 10) + ($codeUnits[$f + 1] & 0x3FF);
                    $f++;
                    $g[$d++] = ($c >> 18) | 0xF0;
                    $g[$d++] = (($c >> 12) & 0x3F) | 0x80;
                    $g[$d++] = (($c >> 6) & 0x3F) | 0x80;
                    $g[$d++] = ($c & 0x3F) | 0x80;
                } else {
                    // 处理三字节UTF-8
                    $g[$d++] = ($c >> 12) | 0xE0;
                    $g[$d++] = (($c >> 6) & 0x3F) | 0x80;
                    $g[$d++] = ($c & 0x3F) | 0x80;
                }
            }
            $f++;
        }
        $a = $h = (int)$e[0];
        foreach ($g as $val) {
            $a += $val;
            $a &= 0xFFFFFFFF;
            // 处理第一个位运算阶段：'+-a^+6'
            $iStr = '+-a^+6';
            $iStrLength = strlen($iStr);
            for ($k = 0; $k < $iStrLength - 2; $k += 3) {
                $op = $iStr[$k];
                $shiftDir = $iStr[$k + 1];
                $jChar = $iStr[$k + 2];
                $j = ord($jChar) >= ord('a') ? (ord($jChar) - 87) : (int)$jChar;
                $jVal = 0;
                if ($shiftDir === '+') {
                    $jVal = ($a & 0xFFFFFFFF) >> $j;
                } else {
                    $jVal = ($a << $j) & 0xFFFFFFFF;
                }
                if ($op === '+') {
                    $a = ($a + $jVal) & 0xFFFFFFFF;
                } else {
                    $a = ($a ^ $jVal) & 0xFFFFFFFF;
                }
            }
        }
        // 处理第二个位运算阶段：'+-3^+b+-f'
        $iStr2 = '+-3^+b+-f';
        $iStr2Length = strlen($iStr2);
        for ($k = 0; $k < $iStr2Length - 2; $k += 3) {
            $op = $iStr2[$k];
            $shiftDir = $iStr2[$k + 1];
            $jChar = $iStr2[$k + 2];
            $j = ord($jChar) >= ord('a') ? (ord($jChar) - 87) : (int)$jChar;
            $jVal = 0;
            if ($shiftDir === '+') {
                $jVal = ($a & 0xFFFFFFFF) >> $j;
            } else {
                $jVal = ($a << $j) & 0xFFFFFFFF;
            }
            if ($op === '+') {
                $a = ($a + $jVal) & 0xFFFFFFFF;
            } else {
                $a = ($a ^ $jVal) & 0xFFFFFFFF;
            }
        }
        // 异或gtk的第二部分并处理负数
        $a ^= (int)$e[1];
        $a &= 0xFFFFFFFF;
        if ($a < 0) {
            $a = ($a & 0x7FFFFFFF) + 0x80000000;
        }
        // 取模并返回结果
        $a = $a % 1000000;
        return $a . '.' . ($a ^ $h);
    }
}
